# encoding : utf-8
class Admin::ProductsController < ApplicationController
  layout 'admin'

  def index
    #@products = Products.paginate(:page => params[:page], :per_page => 10)
    @q = Products.search(params[:q])
    @products = @q.result(:distinct => true)
    @q.build_condition if @q.conditions.empty?
    @q.build_sort if @q.sorts.empty?
  end

  def show
    @product = Products.find_by_id(params[:id])
  end

  def destroy
    @product = Products.find_by_id(params[:id])
    if @product.delete
      flash[:notice] = '删除商品成功!'
      redirect_to admin_products_path
    else
      flash[:notice] = '删除商品失败!'
      redirect_to session[:return_to]
    end
  end

  def update
    @product = Products.find_by_id(params[:id])
    if @product.update_attributes(params[:product])
      flash[:notice] = '更新商品信息成功!'
      redirect_to admin_product_path(@product)
    else
      flash[:error] = '更新商品信息失败!'
      redirect_to edit_product_path(@product)
    end
  end

  def edit
    @product = Products.find_by_id(params[:id])
    render :edit
  end

  def create
    @product = Products.new(params[:product])
    if @product.save
      flash[:notice] = '添加商品成功!'
      redirect_to admin_product_path(@product)
    else 
      flash[:error] = '添加商品失败!'
      render :new
    end
  end

  def new
    @product = Products.new
  end

  def destroy_multiple
    Products.destroy(params[:products])
    redirect_to admin_products_path
  end
end
